var playStatus = 0,  //播放状态
    musicfc = $("audio")[0],  //标签
    volume = 1,
    musicLoop = '',
    arrMusic = new Array(),
    nowPlayNum = 0,  //指针
    onlyLoop = 0,
    arrMusicNum = 0,
    allTime = 0,
    currentnum = 0,
    currentTime = 0,
    lycArray = new Array(),
    musicUrl = '',  //当前播放歌曲
    playHistory = [];

setInterval(function () {
        for (i = 0; i < lycArray.length; i++) {
            if (parseInt(lycArray[i].t) <= parseInt(currentTime + 0.1) && parseInt(lycArray[i + 1].t) >= parseInt(currentTime + 0.1)) {
                currentnum = i;
            }
        }
    },
    1000);

//进度条计算
musicfc.ontimeupdate = function () {
    // if (lycArray.length > 0) {
    //     if (currentnum == lycArray.length - 1 && musicfc.currentTime.toFixed(3) >= parseFloat(lycArray[currentnum].t)) {
    //         $('#lyctext').html(lycArray[currentnum].c);
    //     }
    //     if (parseInt(lycArray[currentnum].t) <= parseInt(musicfc.currentTime + 0.1) && parseInt(musicfc.currentTime + 0.1) <= parseInt(lycArray[currentnum + 1].t)) {
    //         if (musicfc.currentTime > 0) {
    //             $('#lyctext').html(lycArray[currentnum].c);
    //         }
    //         currentnum++;
    //     }
    // }
    //总时长
     allTime = musicfc.duration;
    if (allTime) {
        currentTime = musicfc.currentTime;
        let  allTimeText = transTime(allTime),
            currentTimeText = transTime(currentTime);
        $('#audioTime').html(allTimeText);
        $('#beforeOne').html(currentTimeText);
        $('.circleLight').css('background-color', 'hsla(' + Math.ceil(360 * Math.abs(currentTime / allTime)) + ',80%,50%,0.5)');
        var PlayProgress = Math.round(currentTime / allTime * 10000) / 100;
        $('#PlayProgress').val(PlayProgress);
        $('#PlayProgress').css("background-size", PlayProgress + "% 100%");
    }
};

//播放结束监听
musicfc.addEventListener('ended', function () {
    //随机下一首
    getMusicInfo();
    autoPlay();

    // if (playStatus == 1) {
    //     if (onlyLoop == 0) {
    //         nextMusic();
    //         autoPlay();
    //
    //     }
    // } else {
    //     playStatus = 0;
    //     musicfc.pause();
    //     $(".play").attr("class", 'fa fa-play-circle play');
    //     $('#round_icon').removeClass('play-tx2');
    // }
    // currentnum = 0;
}, false);


// function jsonToArray(json) {
//     arrMusic = new Array();
//     if (json == null && json.toString() == '') {
//         console.log('json error');
//         return false;
//     }
//     for (var item in json) {
//         arrMusic[item] = json[item];
//     }
//     attrMusic(arrMusic[nowPlayNum]);
//     arrMusicNum = arrMusic.length;
// }
//
// jsonToArray(musicJson);

/*****  点击操作 ********/
//开始暂停点击
$('.play').click(function () {
    //测试 随机获取信息
    if (musicUrl === '') {
        //获取歌曲信息
        getMusicInfo();
    }

    if (playStatus === 0) {
        autoPlay();
    } else {
        stopPlay();
    }
});

//上点击
$('.play-left').click(function () {
    prevMusic();
    // if (playStatus == 1) {
    //     autoPlay();
    // }
});

//下点击
$('.play-right').click(function () {
    // nextMusic();
    getMusicInfo();
    stopPlay();

    console.log(playStatus);
    //
    // if (playStatus === 1) {
    //     autoPlay();
    // } else {
    //     stopPlay();
    // }
});

//开始播放
function autoPlay() {
    playStatus = 1;  //修改播放状态
    musicfc.play();
    $(".play").attr("class", 'fa fa-stop-circle play');
    $('#round_icon').addClass('play-tx2');
}

//暂停播放
function stopPlay() {
    playStatus = 0;
    musicfc.pause();
    $(".play").attr("class", 'fa fa-play-circle play');
    $('#round_icon').removeClass('play-tx2');
}

//随机获取歌曲
function getMusicInfo() {
    $.ajax({
        type: 'post',
        url: '/getMusicInfo',
        success: function (res) {
            if (res.code === 0) {
                attrMusic(res.data);
                arrMusicNum = arrMusic.length;
            } else {
                alert('该项目已停止使用！');
                return false;
            }
        },
        error: function () {
            alert('该项目已停止使用！');
            return false;
        }
    });
}

//播放信息渲染
function attrMusic(arr) {
    if (arr && arr.hasOwnProperty('url')) {
        musicfc.src = arr.url.src;
        musicUrl = arr.url.path;
        playHistory.push(arr.id);
        if (arr.pic.src) {
            $('#round_icon').attr("src", arr.pic.src);
        }
        $('.songname').html(arr.title+'-'+arr.author);
        // currentnum = 0;
    } else {
        console.log('noo');
        return false;
    }
}

//歌词渲染
function createLrc(lycText) {
    if (!lycText) {
        return false;
    }
    lycArray = new Array();
    var medises = lycText.split("\n");
    $.each(medises,
        function (i, item) {
            var t = item.substring(item.indexOf("[") + 1, item.indexOf("]"));
            lycArray.push({
                t: (t.split(":")[0] * 60 + parseFloat(t.split(":")[1])).toFixed(3),
                c: item.substring(item.indexOf("]") + 1, item.length)
            });
        });
}

//播放进度
function PlayProgress(val) {
    if (allTime && val) {
        musicfc.currentTime = Math.round(allTime * val / 100);
        $('#PlayProgress').css("background-size", val + "% 100%");
    }
}

function cycle(loop) {
    if (loop == true) {
        musicfc.addEventListener("ended", autoPlay, false);
    } else {
        musicfc.removeEventListener("ended", autoPlay, false);
    }
}

function timeChange(time) {
    var minute = time / 60;
    var minutes = parseInt(minute);
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    var second = time % 60;
    seconds = parseInt(second);
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    var allTimes = "" + minutes + "" + ":" + "" + seconds + ""
    return allTimes;
}

//转换音频时长显示
function transTime(time) {
    let duration = parseInt(time),
        minute = parseInt(duration / 60),
        sec = duration % 60 + '',
        isM0 = ':';
    if (minute === 0) {
        minute = '00';
    } else if (minute < 10) {
        minute = '0' + minute;
    }
    if (sec.length === 1) {
        sec = '0' + sec;
    }
    return minute + isM0 + sec;
}

var dsq;
var scale = function (btn, bar) {
    this.btn = document.getElementById(btn);
    this.bar = document.getElementById(bar);
    this.step = this.bar.getElementsByTagName("DIV")[0];
};
scale.prototype = {
    start: function (x) {
        var f = this,
            g = document,
            b = window,
            m = Math;
        f.btn.style.left = x + 'px';
        this.step.style.width = Math.max(0, x) + 'px';
    }
}

var scale2 = new scale('progressBtn', 'progressBar');
var colseBar = function () {
    clearInterval(dsq);
    dsq = setTimeout(function () {
            $('#progressBar').hide(1000);
        },
        3000);
}

Sition('round_icon', 'clicked',
    function () {
        if (playStatus == 0) {
            autoPlay();
        } else {
            stopPlay();
        }
    });

Sition('fcmusic', 'rightDownIng',
    function () {
        //autoPlay();
        musicfc.currentTime = currentTime + 5;
        console.log(musicfc.currentTime);
        if (musicfc.currentTime > allTime) {
            musicfc.currentTime = allTime;
        }
        currentTime = musicfc.currentTime;
    });

Sition('fcmusic', 'leftDownIng',
    function () {
        musicfc.currentTime = currentTime - 5;
        console.log(musicfc.currentTime);
        if (musicfc.currentTime < 0) {
            musicfc.currentTime = 0;
        }
        currentTime = musicfc.currentTime;
    });

Sition('fcmusic', 'rightCenter',
    function () {
        nextMusic();
        if (playStatus == 1) {
            autoPlay();
        }
    });
Sition('fcmusic', 'leftCenter',
    function () {
        prevMusic();
        if (playStatus == 1) {
            autoPlay();
        }
    });

Sition('fcmusic', 'leftUp',
    function () {
        cycle(true);
        $.alertView("已开启单曲循环");
        onlyLoop = 1;
    });
Sition('fcmusic', 'rightUp',
    function () {
        cycle(false);
        $.alertView("已关闭单曲循环");
        onlyLoop = 0;
    });

Sition('fcmusic', 'upRightIng',
    function (ev) {
        volume += 0.02;
        if (volume > 1) {
            volume = 1;
        }
        $('#progressBar').show();
        musicfc.volume = volume;
        var progressWidth = $('.scale_panel').width();
        if (progressWidth >= progressWidth * volume) {
            scale2.start(progressWidth * volume - 8);
        } else {
            scale2.start(progressWidth * volume);
        }
        colseBar();
    });

Sition('fcmusic', 'downRightIng',
    function (ev) {
        volume -= 0.02;
        if (volume <= 0) {
            volume = 0;
        }
        $('#progressBar').show();
        musicfc.volume = volume;
        var progressWidth = $('.scale_panel').width();
        scale2.start(progressWidth * volume);
        colseBar();
    });

Sition('fcmusic', 'downCenter',
    function (ev) {
        $('#tools').hide();
    });
Sition('fcmusic', 'upCenter',
    function (ev) {
        $('#tools').show();
    });

Sition('fcmusic', 'long',
    function () {
        var msgjson = {
            title: "",
            msg: '<input name="search-name" id="search_name" class="search" type="search" placeholder="请输入歌曲名称" />',
            buttons: [{
                title: "搜索",
                click: function () {
                    var name = $('#search_name').val();
                    $.ajax({
                        url: "search.php?str=" + name,
                        async: false,
                        success: function (result) {
                            if (!result) {
                                $.alertView('无搜索结果');
                            } else {
                                var json2 = eval('(' + result + ')');
                                jsonToArray(json2);
                                autoPlay();

                            }
                        }
                    })
                }
            },
                {
                    title: "取消",
                    color: "red",
                    click: function () {
                    }
                }]
        }
        $.alertView(msgjson);
    });

// function hengshuping() {
//     if (window.orientation == 90 || window.orientation == -90) {
//         $('#tools').hide();
//         $('.block').css('max-width', '1300px');
//         $('.block').css('height', '500px');
//         $('#fcmusic').css('padding', '0,0');
//     }
// }
//
// window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);
//
// if (document.cookie.indexOf("a=hello") == -1) {
//     $.alertView(msgjson);
// }